import {
  autorun,
  reaction,
  intercept,
  extendObservable,
  computed
} from 'mobx';

import registerObject from "./registerObject"

/* 476 */
/***/

function registerObjectFromGuid(g3v, selfObject, guidProperty, objectProperty) {
  var earthObjectProperty = objectProperty;
  var earthObjectGuidProperty = guidProperty;

  var currentAttachedObjectGuid = '';
  var unregisterEarthObject = undefined;
  var attchedObjectDisposers = [];
  attchedObjectDisposers.push(function() {
    currentAttachedObjectGuid = '';
    updateRegisterEarthObject();
  });

  var attachPath = function attachPath(path) {
    if (selfObject[earthObjectProperty]) {
      console.error('this._attachedPath should not exists!');
    }
    selfObject[earthObjectProperty] = path;
  };

  var detachPath = function detachPath() {
    selfObject[earthObjectProperty] = undefined;
  };

  var updateRegisterEarthObject = function updateRegisterEarthObject() {
    var attachedObjectGuid = selfObject[earthObjectGuidProperty];
    if (attachedObjectGuid === currentAttachedObjectGuid) {
      return;
    }

    if (currentAttachedObjectGuid) {
      unregisterEarthObject = unregisterEarthObject && unregisterEarthObject();
      currentAttachedObjectGuid = '';
    }

    if (attachedObjectGuid) {
      unregisterEarthObject = registerObject(g3v, attachedObjectGuid, attachPath,
        detachPath);
      currentAttachedObjectGuid = attachedObjectGuid;
    }
  };

  attchedObjectDisposers.push(autorun(updateRegisterEarthObject));

  return function() {
    attchedObjectDisposers.forEach(function(d) {
      return d();
    });
    attchedObjectDisposers.length = 0;
  };
}

export default registerObjectFromGuid;
